#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int, int>;
#define rep(i, a, b) for (int i = (a); i <= (b); i++)
#define per(i, a, b) for (int i = (a); i >= (b); i--)
#define endl '\n'
const int N = 3e6 + 5;

int n, m;
string s;
int vis[N];
struct Node {
  int a, p, c;
};

void solve() {
  cin >> s;
  n = s.size();
  queue<int> a, p, c;
  vector<Node> res;
  rep(i, 0, n - 1) {
    vis[i] = 0;
    if (s[i] == 'A')
      a.push(i);
    else if (s[i] == 'P')
      p.push(i);
    else
      c.push(i);
  }
  while (a.size()) {
    while (p.size() && p.front() < a.front()) p.pop();
    if (p.empty()) break;
    while (c.size() && c.front() < p.front()) c.pop();
    if (c.empty()) break;
    vis[a.front()] = vis[p.front()] = vis[c.front()] = 1;
    res.push_back(Node{a.front(), p.front(), c.front()});
    a.pop(), p.pop(), c.pop();
  }
  string ans;
  rep(i, 0, n - 1) if (!vis[i]) ans.push_back(s[i]);
  if (ans.empty())
    cout << "Perfect" << endl;
  else
    cout << ans << endl;
  cout << res.size() << endl;
  for (auto x : res)
    cout << x.a + 1 << ' ' << x.p + 1 << ' ' << x.c + 1 << endl;
}
int main() {
  ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  int t;
  cin >> t;
  while (t--) solve();
  return 0;
}